﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SingleBlog.Core.Data;
using SingleBlog.Core.Services;
using System;
using System.Threading.Tasks;

namespace SingleBlog.Web.Areas.Admin.Controllers
{
    [Area("admin")]
    [Authorize(Roles = SingleBlogRole.ADMINISTRATOR)]
    public class CategoryController : Controller
    {
        private readonly CategoryService _categoryService;
        public CategoryController(CategoryService categoryService)
        {
            _categoryService = categoryService;
        }

        public async Task<IActionResult> List()
        {
            var list = await _categoryService.GetCategoriesAsync();
            return View(list);
        }

        public async Task<IActionResult> Edit(int? id)
        {
            if (id.HasValue)
            {
                var category = await _categoryService.GetCategoryAsync(id.Value);
                if (category == null)
                {
                    return NotFound();
                }
                return View(category);
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Edit([FromForm]Category category)
        {
            await _categoryService.SaveCategoryAsync(category);
            return RedirectToAction("List");
        }
        
        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _categoryService.DeleteCategoryAsync(id);
            }catch(Exception ex)
            {
                return BadRequest(ex.Message);
            }
            return Ok();
        }
    }
}
